﻿using AutoMapper;
using KayakMes.Check.Application.Input;
using KayakMes.Check.Domain;
using KayakMes.Common;
using KayakMes.Common.Dtos.CheckDto;
using KayakMes.Common.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using SqlSugar;

namespace KayakMes.Check.Application
{
    public class CheckService : ICheckService
    {
        private readonly BaseReposiotry<CheckWayModel> _checkWayReposiotry;
        private readonly IMapper mapper;
        private readonly ISqlSugarClient _db;

        public CheckService(BaseReposiotry<CheckWayModel> checkWayReposiotry, IMapper mapper, ISqlSugarClient db)
        {
            _checkWayReposiotry = checkWayReposiotry;
            this.mapper = mapper;
            this._db = db;
        }
        /// <summary>
        /// 添加检查方式
        /// </summary>
        /// <param name="checkWay"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult<int> AddCheckWay(AddCheckWayInput checkWay)
        {
            var model=mapper.Map<CheckWayModel>(checkWay);
            model.Id= YitIdHelper.NextId();
            model.CreateTime=DateTime.Now;
            model.CheckCode=GenerateCheckCode();
           var obj=   _checkWayReposiotry.Add(model);
            if(obj>0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "添加检查方式",
                    Data = obj
                };
            }
            else
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "添加检查方式失败",
                    Data = 0
                };
            }

        }
        /// <summary>
        /// 获取单条检查方式
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult< CheckWayModel> CheckWayModel(long Id)
        {
            ApiResult < CheckWayModel > result = new ApiResult< CheckWayModel >();
            var data= _checkWayReposiotry.GetModel(Id);
            result.Code = ApiEnums.Success;
            result.Message = "获取单条检查方式";
            result.Data = data;
            return result;
        }
        /// <summary>
        /// 删除检查方式
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult< int> DeleteCheckWay(long Id)
        {
            ApiResult<int> api= new ApiResult<int>();
            var model = _checkWayReposiotry.GetModel(Id);
            var obj= _checkWayReposiotry.Delete(model);
            if(obj>0)
            {
                api.Data = obj;
                api.Code = ApiEnums.Success;
                api.Message = "删除成功";
            }
            else
            {
                api.Code = ApiEnums.Fail;
                api.Message = "删除失败";
                
            }
            return api;

        }
        /// <summary>
        /// 分页所有检查方式
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiPaging<CheckWayDto> GetAllCheckWay(CheckWayInput input)
        {
            ApiPaging<CheckWayDto> api = new ApiPaging<CheckWayDto>();

            try
            {
                // 构建查询条件
                var query = _checkWayReposiotry.GetAll();

                // 添加筛选条件
                if (!string.IsNullOrEmpty(input.CheckCode))
            {
                    query = query.Where(x => x.CheckCode.Contains(input.CheckCode));
            }
                if (!string.IsNullOrEmpty(input.CheckWayName))
            {
                    query = query.Where(x => x.CheckWayName.Contains(input.CheckWayName));
            }

                // 获取总数（在分页之前）
                int totalCount = query.Count();

                // 执行分页查询
                var pagedData = query
                    .OrderByDescending(x => x.CreateTime) // 按创建时间倒序
                    .Skip((input.PageIndex - 1) * input.PageSize)
                    .Take(input.PageSize)
                    .ToList();

                // 映射到DTO
                var dtoList = mapper.Map<List<CheckWayDto>>(pagedData);

                // 设置返回结果
                api.Code = ApiEnums.Success;
                api.Message = "分页查询成功";
                api.Items = dtoList;
                api.PageIndex = input.PageIndex;
                api.PageSize = input.PageSize;
                api.Total = totalCount;
            }
            catch (Exception ex)
            {
                api.Code = ApiEnums.Fail;
                api.Message = $"分页查询失败：{ex.Message}";
                api.Items = new List<CheckWayDto>();
                api.Total = 0;
            }

            return api;
        }
        /// <summary>
        /// 修改检查方式
        /// </summary>
        /// <param name="checkWay"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult< int> UpdateCheckWay(UpdateCheckWayInput checkWay)
        {
            ApiResult<int> api= new ApiResult< int>();  

            var model = _checkWayReposiotry.GetModel(checkWay.Id);
            mapper.Map(checkWay, model);

           
           var obj=  _checkWayReposiotry.Update(model);
            if(obj>0)
        {
                api.Code=ApiEnums.Success;
                api.Message="修改成功";
                api.Data=obj;
            }
            else
            {
                api.Code=ApiEnums.Fail;
                api.Message="修改失败";
                api.Data=obj;
            }
            return api;
        }
        /// <summary>
        /// 生成检验编码
        /// </summary>
        /// <returns></returns>
        public string GenerateCheckCode()
        {
            try
            {
                // 获取所有检验编码，按CheckCode排序
                var allCheckCodes = _checkWayReposiotry.GetAll()
                    .Where(x => !string.IsNullOrEmpty(x.CheckCode) && x.CheckCode.StartsWith("MESCheck"))
                    .OrderByDescending(x => x.CheckCode)
                    .Select(x => x.CheckCode)
                    .ToList();

                int nextNumber = 1; // 默认从1开始

                if (allCheckCodes.Any())
                {
                    // 获取最大的编号
                    var maxCode = allCheckCodes.First();
                    
                    // 提取数字部分
                    if (maxCode.Length > 8) // "MESCheck".Length = 8
                    {
                        var numberPart = maxCode.Substring(8); // 去掉"MESCheck"前缀
                        if (int.TryParse(numberPart, out int currentNumber))
                        {
                            nextNumber = currentNumber + 1;
                        }
                    }
                }

                // 格式化为3位数字，不足补0
                return $"MESCheck{nextNumber:D3}";
            }
            catch (Exception ex)
            {
                // 如果出现异常，返回默认编码
                return "MESCheck001";
            }
        }
    }
}
